async function fetchEmployees() {
    try {
        const response = await fetch('/api/employees', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        });
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log('Received data:', data);
        displayEmployees(data);
    } catch (error) {
        console.error('Error fetching employees:', error);
        alert('获取员工数据失败，请检查控制台日志');
    }
}

function getDepartmentIcon(department) {
    const icons = {
        '技术部': 'images/department-icons/tech.png',
        '人事部': 'images/department-icons/hr.png',
        '财务部': 'images/department-icons/finance.png',
        '市场部': 'images/department-icons/marketing.png'
    };
    return icons[department] || 'images/department-icons/default.png';
}

// 显示员工列表
function displayEmployees(employees) {
    const tbody = document.getElementById('employeeList');
    tbody.innerHTML = '';
    
    employees.forEach((emp, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${index + 1}</td>
            <td>
                <img src="images/avatar-default.png" class="employee-avatar" alt="Avatar">
                ${emp.name}
            </td>
            <td>
                <img src="${getDepartmentIcon(emp.department)}" class="department-icon" alt="${emp.department}">
                ${emp.department}
            </td>
            <td>${emp.position}</td>
            <td>
                <button onclick="editEmployee(${emp.id})" class="btn-edit">
                    <i class="fas fa-edit"></i>
                </button>
                <button onclick="deleteEmployee(${emp.id})" class="btn-delete">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 添加员工
async function addEmployee(employee) {
    try {
        const response = await fetch('/api/employees', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(employee)
        });
        if (response.ok) {
            await fetchEmployees();
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

// 删除员工
async function deleteEmployee(id) {
    if (confirm('确定要删除这名员工吗？')) {
        try {
            const response = await fetch(`/api/employees/${id}`, {
                method: 'DELETE'
            });
            if (response.ok) {
                await fetchEmployees();
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }
}

// 编辑员工
async function editEmployee(id) {
    try {
        // 获取当前员工信息
        const response = await fetch(`/api/employees/${id}`);
        const employee = await response.json();
        
        // 显示编辑表单
        const updatedEmployee = {
            id: employee.id,
            name: prompt('请输入员工姓名：', employee.name),
            department: showDepartmentSelector(employee.department),
            position: prompt('请输入职位：', employee.position)
        };
        
        if (updatedEmployee.name && updatedEmployee.department && updatedEmployee.position) {
            // 发送更新请求
            const updateResponse = await fetch(`/api/employees/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(updatedEmployee)
            });
            
            if (updateResponse.ok) {
                await fetchEmployees();
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

// 显示部门选择器
function showDepartmentSelector(currentDepartment) {
    const departments = ['技术部', '市场部', '人事部', '财务部'];
    let options = departments.map(dept => 
        `<option value="${dept}" ${dept === currentDepartment ? 'selected' : ''}>${dept}</option>`
    ).join('');
    
    const selectHtml = `
        <select id="departmentSelect">
            ${options}
        </select>
    `;
    
    const wrapper = document.createElement('div');
    wrapper.innerHTML = selectHtml;
    
    const result = prompt('请选择部门（或直接输入新部门）：', currentDepartment);
    return result || currentDepartment;
}

// 添加员工时也使用部门选择器
function showAddEmployeeForm() {
    const employee = {
        name: prompt('请输入员工姓名：'),
        department: showDepartmentSelector('技术部'), // 默认选择技术部
        position: prompt('请输入职位：')
    };
    
    if (employee.name && employee.department && employee.position) {
        addEmployee(employee);
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', fetchEmployees); 